package com.etung.iot.demo.services.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.etung.iot.demo.dao.ProjectMapper;
import com.etung.iot.demo.dao.UserMapper;
import com.etung.iot.demo.modles.ProjectEntity;
import com.etung.iot.demo.modles.UserEntity;
import com.etung.iot.demo.services.UserService;
import com.etung.iot.demo.utils.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.Queue;
import java.util.UUID;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ProjectMapper projectMapper;


    @Transactional
    @Override
    public void register(UserEntity user) {
        UserEntity oldUser = userMapper.selectOne(new QueryWrapper<UserEntity>().eq("username", user.getUsername()));
        if(oldUser == null){
            UserEntity userEntity = new UserEntity();
            userEntity.setId(UUID.randomUUID().toString().replace("-", ""));
            userEntity.setUsername(user.getUsername());
            userEntity.setSalt(MD5Util.randomGen(8));
            userEntity.setPassword(MD5Util.stringToMD5(user.getPassword()+userEntity.getSalt()));
            userEntity.setCreateTime(new Date());
            userMapper.insert(userEntity);
            //创建系统默认项目组
            ProjectEntity projectEntity = new ProjectEntity();
            projectEntity.setUserId(userEntity.getId());
            projectEntity.setName("默认组");
            projectEntity.setDelFlag(0).setCreateTime(new Date());
            projectMapper.insert(projectEntity);
        }else{
            throw new RuntimeException("当前用户名已存在!");
        }
    }

    @Transactional
    @Override
    public String login(UserEntity user) {
        UserEntity oldUser = userMapper.selectOne(new QueryWrapper<UserEntity>().eq("username", user.getUsername()));
        if(oldUser == null){
            throw new RuntimeException("用户名或密码错误!");
        }
        String encryptPassword = MD5Util.stringToMD5(user.getPassword()+oldUser.getSalt());
        if(!oldUser.getPassword().equals(encryptPassword)){
            throw new RuntimeException("用户名或密码错误!");
        }
        return generateToken(oldUser.getId(),oldUser.getPassword());
    }

    @Override
    public String generateToken(String userId,String password) {
        return JWT.create().withAudience(userId)
                .sign(Algorithm.HMAC256(password));
    }

    @Override
    public String retrieveUserIdFromToken(String token) {
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        return JWT.decode(token).getAudience().get(0);
    }

    @Override
    public UserEntity selectByPrimaryKey(String userId){
        return userMapper.selectById(userId);
    }

}
